import { LockOutlined, UserOutlined, SafetyCertificateOutlined } from '@ant-design/icons';
import { Button, Form, message, Input, Row, Col, Image } from 'antd';
import { apiInterceptors, loginApi, ldapLogin, getUserInfo, getCaptcha } from '@/client/api';
import { setToken, setUserInfo } from '@/utils/auth';
import { useRouter } from 'next/router';
const bcrypt = require('bcryptjs');

import { useEffect, useState } from 'react';
import classes from '../../index.module.scss';

const LoginForm = (props: any) => {
  const [form] = Form.useForm();
  const [isReg, setIsReg] = useState('true');
  const [captchaText, setCaptchaText] = useState('')
  const [src, setSrc] = useState('')

  const router = useRouter()
  const onFinish = async (param: any) => {
    const salt = bcrypt.genSaltSync(10);
    const requestParam = {
      ...param,
      salt,
      password: bcrypt.hashSync(param.password, salt),
      captcha_text: captchaText
    }
    try {
      let [_, result] = await apiInterceptors(loginApi({ ...requestParam }));
      setToken(`${result.token.access_token}`);
      setUserInfo(result.user)
      router.push('/tenant')
      message.success('登录成功');
    } catch (error) {}
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };
  function queryURLParams(url):{code: string} {
    let pattern = /(\w+)=(\w+)/ig;
    let parames = {};
    url.replace(pattern, ($, $1, $2) => {
      parames[$1] = $2;
    });
    return parames;
  }
  const LdapHandle = async () => {
    const clientId = 'CRDIGITAL_MarvelGPT'
    const domain:string = window.location.host
    const protocol = window.location.protocol
    window.location.href = `https://ldap-uat.crc.com.cn/idp/authCenter/authenticate?response_type=code&state=1&redirect_uri=${protocol}//${domain}/login&client_id=${clientId}`

  }

  const judgeLdapLogin = async () => {
    let queryParam: any = queryURLParams(window.location.href)
    if (queryParam && queryParam.code) {
      const code: string = queryParam.code
      const [_, data] = await apiInterceptors(ldapLogin({code}))
      setToken(`${data.token.access_token}`);
      setUserInfo(data.user)
      router.push('/tenant')
    }
  }
  const getCaptchaImage = async () => {
    const [_, data] = await apiInterceptors(getCaptcha())
    setCaptchaText(data.captcha_text.join(''))
    setSrc('data:image/jpeg;base64,' + data.captcha_image)
  }
  useEffect(() => {
    judgeLdapLogin()
    getCaptchaImage()
  }, [])
  return (

    <>
    <div className={classes['title-container']}>
      <h3 className={classes.title}>欢迎登录MarvelGPT</h3>
    </div>
  <Form
      form={form}
      name="normal_login"
      className={classes['login-form']}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
      layout='vertical'
      requiredMark={false}
    >

      <Form.Item
        name="username"
        label='用户名'
        rules={[
          {
            required: true,
            message: '请输入账号',
          },
        ]}
      >
        <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="账号" />
      </Form.Item>
      <Form.Item
        name="password"
        label='密码'
        rules={[
          {
            required: true,
            message: '请输入密码'
          },
        ]} // 此处password如果使用min，max正则，则初始值无法被检测到，换成pattern则无问题
      >
        <Input.Password prefix={<LockOutlined className="site-form-item-icon" />} type="password" placeholder="请输入密码" />
      </Form.Item>
      <Row gutter={24}>
        <Col flex="auto">
          <Form.Item
            name="user_input_captcha"
            rules={[
              {
                required: true,
                message: '请输入验证码!',
              },
            ]}
          >
            <Input prefix={<SafetyCertificateOutlined />} autoComplete="off" placeholder="验证码" />
          </Form.Item>
        </Col>
        <Col flex="120px">
          {/*{svgCode.img ? (*/}
          {/*  <div onClick={getCaptchaImage} dangerouslySetInnerHTML={{ __html: parseSVG(svgCode.img) }} style={{ cursor: 'pointer', height: `${46}px` }} />*/}
          {/*) : (*/}

          {/*)}*/}
          <Image
            onClick={getCaptchaImage}
            width={200}
            height={46}
            preview={false}
            style={{ cursor: 'pointer' }}
            src={src}
            // eslint-disable-next-line max-len
            fallback=""
          />
        </Col>
      </Row>

      <Form.Item>

        <div style={{ flex: 1 }}>
          <a hidden={isReg !== 'true'} onClick={() => LdapHandle()} style={{ float: 'right' }}>
            Ldap登录
          </a>
        </div>
      </Form.Item>
      {/*<Button className={`login-form-button ${classes['login-btn']}`} onClick={() => form.resetFields()}>*/}
      {/*  重置*/}
      {/*</Button>*/}
      <Button type="primary" htmlType="submit" className={`login-form-button ${classes['login-btn']}`}>
        登录
      </Button>
    </Form>
      </>
  );
};

export default LoginForm;
